#include "MyLineEdit.h"
#include "DebugTool.h"
#include <QtWidgets>
MyLineEdit::MyLineEdit(QWidget* parent)
    : QLineEdit(parent)
{
    // width 188  heigth 50 charWidth = 13;

    QFont font("consoles",14,QFont::Bold);
    setFont (font);
    QFontMetrics mc(font);
    charWidth = mc.averageCharWidth();
//    cout << charWidth;
    setFixedWidth (188 );
    setFixedHeight (50);

    this->setMaxLength (14);
    this->setAlignment (Qt::AlignRight);

//    cout << width () << height ();

//    this->setText ("00");
//    setCursorPosition (0);

    // 如果字符串里有非数字，则撤销操作
    connect (this,&QLineEdit::textChanged,[this](QString txt){
//        cout << txt;
        QRegExp reg("\\D");
        bool ctns = txt.contains (reg);
//        cout << ctns;
        if( ctns )
            this->undo ();
    });

}

void MyLineEdit::paintEvent(QPaintEvent* event)
{
    QFontMetrics mc = this->fontMetrics ();
    charWidth = mc.horizontalAdvance('8');

    QLineEdit::paintEvent(event);

    QPainter painter(this);

    QPen pen;

    for (int i = 1; i < 14; ++i) {
        pen.setWidth (0);
        pen.setColor (QColor(161, 230, 211));   // 浅绿色

        if(i%4==0){
            pen.setWidth (2);
            pen.setColor (Qt::gray);          // 灰色
        }

        if(i == 12){
            pen.setColor(QColor(255, 37, 37)); // 红色
        }
        painter.setPen (pen);
        painter.drawLine(  i * (charWidth)+2, 0, i * (charWidth)+2, height());

    }
}

/**
  * @brief :        重写mouseDoubleClickEvent，双击edt，如果值是0，则角、分位置自动添加字符0，并移动光标
  * @param :     QMouseEvent *
  * @retval: None
  */
void MyLineEdit::mouseDoubleClickEvent(QMouseEvent *)
{
    QString txt = text ();
    long long num = txt.toULongLong ();
    if(num == 0){
        setText ("00");
        setCursorPosition (0);
    }else{
        setCursorPosition (txt.length () - 2);
    }
}
/**
  * @brief :    重写离开事件，鼠标移开后，如果内容的值是0，就清空所有内容
  * @param : QEvent *
  * @retval: None
  */
void MyLineEdit::leaveEvent(QEvent *)
{
    QString txt = text ();
    long long num = txt.toULongLong ();
    if(num == 0){
        setText ("");
    }
}


